package org.onvivals.app.ai.tts.model.cosyVoice;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesisAudioFormat;
import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesisParam;
import com.alibaba.dashscope.audio.ttsv2.SpeechSynthesizer;
import lombok.extern.slf4j.Slf4j;
import org.onvivals.app.ai.tts.AbstractTtsService;
import org.onvivals.common.utils.FFmpegUtils;
import org.onvivals.module.pms.entity.PmsRole;

import java.io.File;
import java.nio.ByteBuffer;
import java.util.Optional;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j
public class CosyVoiceTtsService extends AbstractTtsService {

	private JSONObject ttsConfig;

	private static final Lock lock = new ReentrantLock();

	private PmsRole role;

	public CosyVoiceTtsService(JSONObject config, PmsRole roles) {
		this.ttsConfig = config;
		this.role = roles;
	}
	public CosyVoiceTtsService() {
	}

	public static String generateFilePath() {
		lock.lock();
		try {
			String tmpDir = System.getProperty("java.io.tmpdir");
			String uniqueId = IdUtil.getSnowflakeNextIdStr();
			return tmpDir + uniqueId + ".mp3";
		} finally {
			lock.unlock();
		}
	}

	@Override
	public Optional<String> speechSynthesizer(String id, String content) {
		String key = ttsConfig.getStr("key");
		String targetModel = ttsConfig.getStr("model");
		String voiceId =  "";
		System.out.println("角色:"+ JSONUtil.toJsonStr(role));
		if (StrUtil.isNotEmpty(role.getVoiceType())){
			voiceId = role.getVoiceType();
		}else {
			voiceId = ttsConfig.getStr("voice_type");
		}
		String filePath = generateFilePath();
		// 使用复刻的声音来合成文本为语音
		SpeechSynthesisParam param = SpeechSynthesisParam.builder()
				.format(SpeechSynthesisAudioFormat.MP3_16000HZ_MONO_128KBPS)
				.apiKey(key)
				.model(targetModel)
				.voice(voiceId)
				.build();
		SpeechSynthesizer synthesizer = new SpeechSynthesizer(param, null);
		ByteBuffer audio = synthesizer.call(content);
		// 保存合成的语音到文件
		if (StrUtil.isNotEmpty(synthesizer.getLastRequestId())){
			byte[] bytes = audio.array();
			File f = new File(filePath);
			FileUtil.writeBytes(bytes,f);
			return Optional.of(f.getAbsolutePath());
		}else {
			log.error("ReechoTtsService error");
		}
		return Optional.empty();
	}

}
